<?php
/**
 * Created by PhpStorm
 * User: rain
 * Date: 2018/12/26
 * Time: 下午5:23
 */

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Event;


/**
 * Class BookChapter
 * @property integer $id
 * @property integer $book_id
 * @property string $name
 * @property integer $sort
 * @property string $book_txt
 * @property integer $word_ct
 * @property integer $is_free
 * @property integer $price
 * @property string $created_at
 * @property string $updated_at
 * @property string $paragraphs
 * @package App\Models
 */
class BookChapter extends Model
{
    protected $table   = 'book_chapter';
    protected $guarded = ['id'];

    public function book()
    {
        return $this->belongsTo(Book::class);
    }

    public function words()
    {
        return $this->hasMany(BookWord::class, 'book_chapter_id', 'id')->orderBy('sort', 'asc');
    }

    const FREE_NO  = 0;
    const FREE_YES = 1;
    public static $isFreeLabels = [
        self::FREE_NO => '不免费',
        self::FREE_YES => '免费',
    ];


    protected static function boot()
    {
        parent::boot();

        // 保存前
        //        static::saving(function ($model){
        //            // 检测指定字段变更或新增
        //            if ($model->isDirty('book_txt') || $model->wasRecentlyCreated){
        //                // 创建事件实例并直接处理
        //                $event = new \App\Events\BookChapterTxtChanged($model);
        //                $event->handle(); // 直接执行事件逻辑
        //            }
        //        });

        // 保存后   也可以监听 saved 事件，此时数据已经保存到数据库
        static::saved(function ($chapter){
            if ($chapter->wasChanged('book_txt') || $chapter->wasRecentlyCreated){
                // 创建事件实例并直接处理
                $event = new \App\Events\BookChapterTxtChanged($chapter);
                $event->handle(); // 直接执行事件逻辑
            }
        });
    }

}
